package org.example.java.util.concurrency.catch_exception;

import com.sun.istack.internal.NotNull;

import java.util.concurrent.*;

/**
 * Created by Juntao.Zhang on 2014/10/25.
 */
public class HandlerThreadFactoryTest {
  static class MyRunner implements Runnable {
    public void run() {
//      Thread t = Thread.currentThread();
//      System.out.println("run() by " + t);
//      System.out.println("eh=" + t.getUncaughtExceptionHandler());
      throw new RuntimeException("exception in thread");
    }
  }

  static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
      System.err.println("caught " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }

  static class HandlerThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(@NotNull Runnable r) {
      System.out.println(this + " creating new Thread");
      Thread t = new Thread(r);
      System.out.println("created " + t + " ID:" + t.getId());
      t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
      System.out.println("eh=" + t.getUncaughtExceptionHandler());
      return t;
    }
  }

  public static void main(String[] args) {
    ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
    exec.execute(new MyRunner());
  }
}
